package com.sunday.pinxinghui.model.mine;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.SpannalbeStringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.common.widgets.signcalendar.MonthSignData;
import com.sunday.common.widgets.signcalendar.MonthSignView;
import com.sunday.common.widgets.signcalendar.SignCalendar;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.entity.Member;
import com.sunday.pinxinghui.entity.Sign;
import com.sunday.pinxinghui.entity.SignDay;
import com.sunday.pinxinghui.network.ApiClient;
import com.sunday.pinxinghui.utils.StringOrDate;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sunday.pinxinghui.R.id.textView;

/**
 * Created by 刘涛 on 2017/8/11.
 */

public class SignActivity extends BaseActivity {

    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.user_logo)
    CircleImageView userLogo;
    @Bind(R.id.user_name)
    TextView userName;
    @Bind(R.id.user_point)
    TextView userPoint;
    @Bind(R.id.btn_sign)
    TextView btnSign;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.signcalendar)
    MonthSignView signcalendar;

    long memberId;
    SignCalendar signCalendar1;
    MonthSignData monthSignData;
    Date date;
    List<Date> dates;
    Member member;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign);
        ButterKnife.bind(this);
        titleView.setText("每日签到");
        initView();
        memberId = BaseApplication.getInstance().getMember().getId();
        //memberId = Constants.TEST_MEMBERID;
        signCalendar1 = new SignCalendar(mContext);
        signcalendar.setSignCalendar(signCalendar1);
        getMember();
    }

    private void getMember() {
        Call<ResultDO<Member>> call = ApiClient.getApiAdapter().getMember(memberId);
        call.enqueue(new Callback<ResultDO<Member>>() {
            @Override
            public void onResponse(Call<ResultDO<Member>> call, Response<ResultDO<Member>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0)
                    member = response.body().getResult();
                if (!TextUtils.isEmpty(member.getLogo())) {
                    Picasso.with(mContext)
                            .load(member.getLogo())
                            .error(R.mipmap.ic_default)
                            .into(userLogo);
                }
                userName.setText(member.getNickName());
                userPoint.setText("总积分："+String.valueOf(member.getScore()));
                getSignList();
            }

            @Override
            public void onFailure(Call<ResultDO<Member>> call, Throwable t) {

            }
        });
    }

    private void initView() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        tvTitle.setText(year + "年" + month + "月");
        date = new Date();
        monthSignData = new MonthSignData();
        monthSignData.setYear(date.getYear() + 1900);
        monthSignData.setMonth(date.getMonth());
        dates = StringOrDate.getAllDateOftheMonth(new Date());
    }

    private Sign signData;

    private void getSignList() {
        showLoadingDialog(0);
        Call<ResultDO<Sign>> call = ApiClient.getApiAdapter().getSignList(memberId);
        call.enqueue(new Callback<ResultDO<Sign>>() {
            @Override
            public void onResponse(Call<ResultDO<Sign>> call, Response<ResultDO<Sign>> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                ResultDO<Sign> resultDO = response.body();
                if (resultDO.getCode() == 0 && resultDO.getResult() != null) {
                    signData = resultDO.getResult();
                    updateView();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Sign>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private ArrayList<Date> signDates = new ArrayList<>();

    private void updateView() {
        btnSign.setText(signData.getIsTodaySign() == 1 ? "已签" : "签到");
        List<SignDay> signDate = signData.getList();
        for (SignDay item : signDate) {
            if (item.getStatus() == 1) {
                signDates.add(dates.get(item.getDay() - 1));
            }
        }
        monthSignData.setSignDates(signDates);
        signcalendar.setMonthSignData(monthSignData);
    }

    @OnClick({R.id.btn_sign, R.id.btn_integral})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_sign:
                if (signData == null || signData.getIsTodaySign() == 1) {
                    return;
                }
                showLoadingDialog(0);
                Call<ResultDO<Sign>> call = ApiClient.getApiAdapter().sign(memberId);
                call.enqueue(new Callback<ResultDO<Sign>>() {
                    @Override
                    public void onResponse(Call<ResultDO<Sign>> call, Response<ResultDO<Sign>> response) {
                        dissMissDialog();
                        ResultDO<Sign> resultDO = response.body();
                        if (resultDO == null) {
                            return;
                        }
                        if (resultDO.getCode() == 0 && resultDO.getResult() != null) {
                            signData = resultDO.getResult();
                            backgroundAlpha(0.7f);
                            showPopupwindow(signData.getScore());
                            btnSign.setText("已签");
                            userPoint.setText(String.valueOf(member.getScore() + signData.getScore()));
                            signDates.add(date);
                            monthSignData.getSignDates().add(date);
                            monthSignData.setSignDates(signDates);
                            signcalendar.removeAllViews();
                            signcalendar.setSignCalendar(new SignCalendar(mContext));
                            signcalendar.setMonthSignData(monthSignData);


                        } else {
                            ToastUtils.showToast(mContext, resultDO.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(Call<ResultDO<Sign>> call, Throwable t) {
                        ToastUtils.showToast(mContext, R.string.network_error);
                    }
                });
                break;
            case R.id.btn_integral:
                intent = new Intent(mContext, MyIntegralActivity.class);
                startActivity(intent);
                break;
        }
    }


    PopupWindow popupWindow;

    //显示PopupWindow
    private void showPopupwindow(int score) {
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
        popupWindow = new PopupWindow(mContext);
        popupWindow.setOnDismissListener(new PoponDismissListener());
        View view = getWindow().getLayoutInflater().inflate(R.layout.sign_window, null);
        popupWindow.setContentView(view);
        popupWindow.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        // 使其聚集
        popupWindow.setFocusable(true);
        // 设置不允许在外点击消失
        popupWindow.setOutsideTouchable(false);
        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
        ((TextView) view.findViewById(R.id.sign_today_score)).setText("+" + score);
        ((TextView) view.findViewById(R.id.sign_title)).setText("签到领取积分" + score + "分");
        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });


    }

    /**
     * 弹出的popWin关闭的事件，主要是为了将背景透明度改回来
     *
     * @author cg
     */
    class PoponDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            backgroundAlpha(1f);
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }


}
